<?php
function smarty_function_countries($params, &$smarty){
	$oCountries = new Models_Locations_Countries();//Models_Countries();
	$countries = $oCountries->getAll(NULL,'country_name');

	$output = "<select name='".$params['name']."' id='".$params['name']."_id' size='1'>\n";
	foreach($countries as $country){
		if($params['value']==$country->country_id){
			$selected = "selected='selected'";			
		}else{
			$selected='';	
		}
		
		if($params['regions_field']){
			$onclick = 'getRegionsByCountry_'.$params['regions_field'].'(this.value,\''.$params['regions_field'].'\')';
		}else{
			$onclick = '';
		}
		
		$output.="<option onclick=\"$onclick\" $selected value='".$country->country_id."'>".$country->country_name."</option>\n";
	}	
	$output.='</select>';
	
	echo $output;
	
	
	if($params['regions_field']){
		$selected_value = ($params['value'])?$params['value']:$countries[0]->country_id;
		echo  <<<END
		<script type="text/javascript">		
		function getRegionsByCountry_{$params['regions_field']}(country_id,region_field_id){
			$.ajax({
		            type: "GET",
		            url: '/locations/index/statebycountry/country_id/'+country_id,
		            dataType: "json",
		            success : addRegions_{$params['regions_field']}
		     });
		}

		function addRegions_{$params['regions_field']}(json){
			$('#{$params['regions_field']}_id').html('');

			for(i=0; i<json.regions.length;i++){
				if(json.current_region == json.regions[i].country_region_id){
					selected = "selected='selected'";
				}else{
					selected = "";
				}

				$('#{$params['regions_field']}_id').append("<option value='"+json.regions[i].country_region_id+"'" + selected + ">" + json.regions[i].country_region_name +"</option>");
			}
		}
		
		$(document).ready(function()  
		 {  
		    getRegionsByCountry_{$params['regions_field']}($selected_value, '{$params['regions_field']}');  
		 });		
		</script>
END;
	}
}
